package com.shd.edanpei.util;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by TYF on 2017/7/21.
 * 管理同一个activity中fragment切换的工具类
 */

public class FragmentUtil {
    private FragmentManager mFragmentManager;
    private Map<Integer, Fragment> mFragmentMap;//存储fragment的map,键=RadioButton的id，值=对应的Fragment实例
    int mLayoutId;//FrameLayout
    int mCurrentId = -1;//当前显示的Fragment对应的键

    public FragmentUtil(FragmentManager fragmentManager, int layoutId) {
        mFragmentManager = fragmentManager;
        mLayoutId = layoutId;
        mFragmentMap = new HashMap<>();
    }

    /**
     * 添加Fragment
     *
     * @param id
     * @param fragment
     */
    public void add2Map(Fragment fragment, int id) {
        mFragmentMap.put(id, fragment);
         mFragmentManager.beginTransaction().add(mLayoutId, fragment).commitAllowingStateLoss();
    }

    /**
     * 添加Fragment并显示
     *
     * @param fragment
     * @param id
     */
    public void addShow(Fragment fragment, int id) {
        mFragmentMap.put(id, fragment);
        mFragmentManager.beginTransaction().add(mLayoutId, fragment).show(fragment).commitAllowingStateLoss();
        mCurrentId = id;
    }

    /**
     * map中是否包含对应的fragment
     *
     * @param id
     * @return
     */
    public boolean hasFragment(int id) {
        return mFragmentMap.containsKey(id);
    }


    /**
     * 切换tab
     *
     * @param preId
     * @param nowId
     */
    public void changeTab(int preId, int nowId) {
        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
        Fragment preF = mFragmentMap.get(preId);
        if (preF != null) {
            fragmentTransaction.hide(preF);
        }
        Fragment nowF = mFragmentMap.get(nowId);
        if (nowF != null) {
            fragmentTransaction.show(nowF);
        }
        fragmentTransaction.commitAllowingStateLoss();
    }

    /**
     * 显示指定Fragment
     *
     * @param id
     */
    public void changeTab(int id) {
        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
        if (mCurrentId != -1)
            fragmentTransaction.hide(mFragmentMap.get(mCurrentId));
        mCurrentId = id;
        fragmentTransaction.show(mFragmentMap.get(mCurrentId));
        fragmentTransaction.commitAllowingStateLoss();
    }

    /**
     * 获取当前的id
     *
     * @return
     */
    public int getCurrentId() {
        return mCurrentId;
    }

    /**
     * 获取Fragment
     *
     * @param id
     * @return
     */
    public Fragment getF(int id) {
        return mFragmentMap.get(id);
    }
}
